package com.heima.controller;

import com.heima.annotation.GlobalInterceptor;
import com.heima.entity.dto.SessionShareDto;
import com.heima.entity.dto.SessionWebUserDto;
import com.heima.entity.enums.FileDelFlagEnums;
import com.heima.entity.enums.FileFolderTypeEnums;
import com.heima.entity.enums.FileStatusEnums;
import com.heima.entity.enums.ResponseCodeEnum;
import com.heima.entity.po.FileInfo;
import com.heima.entity.po.FileShare;
import com.heima.entity.po.UserInfo;
import com.heima.entity.query.FileInfoQuery;
import com.heima.entity.query.FileShareQuery;
import com.heima.entity.vo.FileInfoVO;
import com.heima.entity.vo.PaginationResultVO;
import com.heima.entity.vo.ResponseVO;
import com.heima.entity.vo.ShareInfoVO;
import com.heima.exception.BusinessException;
import com.heima.service.FileInfoService;
import com.heima.service.FileShareService;
import com.heima.service.UserInfoService;
import com.heima.utils.CopyTools;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/showShare")
public class ShowShareController extends CommonFileController{
    @Resource
    private FileShareService fileShareService;
    @Resource
    private FileInfoService fileInfoService;
    @Resource
    private UserInfoService userInfoService;

    @RequestMapping("/getShareLoginInfo")
    @GlobalInterceptor(checkLogin = false)
    public ResponseVO getShareLoginInfo(HttpSession session,String shareId){
        SessionShareDto sessionShareFromSession = getSessionShareFromSession(session, shareId);
        if (sessionShareFromSession == null){
            return getSuccessResponseVO(null);
        }
        ShareInfoVO shareInfoCommon = getShareInfoCommon(shareId);
        //判断是否为当前用户分享的文件
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        if (webUserDto != null && shareInfoCommon.getUserId().equals(webUserDto.getUserId())){
            shareInfoCommon.setCurrentUser(true);
        }else {
            shareInfoCommon.setCurrentUser(false);
        }
        return getSuccessResponseVO(shareInfoCommon);
    }
    @RequestMapping("/getShareInfo")
    @GlobalInterceptor(checkLogin = false)
    public ResponseVO getShareInfo(HttpSession session,String shareId){

        return getSuccessResponseVO(getShareInfoCommon(shareId));
    }

    @RequestMapping("/loadFileList")
    @GlobalInterceptor(checkLogin = false)
    public ResponseVO loadFileList(HttpSession session,String shareId,String filePid){
        checkShare(session,shareId);

        FileShare share = fileShareService.getFileShareByShareId(shareId);
        FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(share.getFileId(),share.getUserId());

        FileInfoQuery query = new FileInfoQuery();


        query.setUserId(share.getUserId());
        query.setDelFlag(FileDelFlagEnums.USING.getFlag());
        query.setStatus(FileStatusEnums.USING.getStatus());
        query.setOrderBy("folder_type desc , last_update_time desc");
        if (!filePid.equals("0")){
            query.setFilePid(filePid);
        }else {

            query.setFileId(share.getFileId());
        }


        PaginationResultVO<FileInfo> listByPage = fileInfoService.findListByPage(query);
        List<FileInfoVO> retrunList = CopyTools.copyList(listByPage.getList(), FileInfoVO.class);
        PaginationResultVO<FileInfoVO> listReturn = new PaginationResultVO<>();
        BeanUtils.copyProperties(listByPage,listReturn);
        listReturn.setList(retrunList);
        return getSuccessResponseVO(listReturn);
    }

    @RequestMapping("/checkShareCode")
    @GlobalInterceptor(checkLogin = false)
    public ResponseVO checkShareCode(HttpSession session,String shareId,String code){
        fileShareService.checkShareCode(session,shareId,code);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/getFolderInfo")
    @GlobalInterceptor(checkLogin = false)
    public ResponseVO getFolderInfo(HttpSession session,String shareId,String path){
        checkShare(session,shareId);
        FileShare share = fileShareService.getFileShareByShareId(shareId);
        return super.getFolderInfo(path,share.getUserId());

    }

    @RequestMapping("/ts/getVideoInfo/{shareId}/{fileId}")
    @GlobalInterceptor(checkLogin = false)
    public void getVideoInfo(HttpSession session,HttpServletResponse response, @PathVariable("shareId") String shareId,@PathVariable("fileId") String fileId){
        checkShare(session,shareId);
        FileShare share = fileShareService.getFileShareByShareId(shareId);
        super.getFile(response, fileId, share.getUserId());

    }

    @RequestMapping("/getFile/{shareId}/{fileId}")
    @GlobalInterceptor(checkLogin = false)
    public void getFile(HttpSession session,HttpServletResponse response,@PathVariable("shareId") String shareId,@PathVariable("fileId") String fileId){
        SessionShareDto share = checkShare(session, shareId);
//        FileShare share = fileShareService.getFileShareByShareId(shareId);
        super.getFile(response,fileId, share.getShareUserId());
    }

    @RequestMapping("/createDownloadUrl/{shareId}/{fileId}")
    @GlobalInterceptor()
    public ResponseVO createDownloadUrl(HttpSession session,@PathVariable("shareId") String shareId,@PathVariable("fileId") String fileId){
        SessionShareDto share = checkShare(session, shareId);
//        FileShare share = fileShareService.getFileShareByShareId(shareId);
        return super.createDownloadUrl(fileId,share.getShareUserId());
    }

    @RequestMapping("/download/{code}")
    @GlobalInterceptor
    public void downloadCode(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response){
        try {
            super.download(request,response,code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/saveShare")
    @GlobalInterceptor
    public ResponseVO saveShare(HttpSession session,String shareId,String shareFileIds,String myFolderId){
        SessionShareDto shareDto = checkShare(session, shareId);
        SessionWebUserDto webUserDto = getUserInfoFromSession(session);
        if (shareDto.getShareUserId().equals(webUserDto.getUserId())){
            throw new BusinessException("自己分享的文件无法保存到自己的网盘");
        }
        fileShareService.savaShare1(shareId,shareFileIds,myFolderId,shareDto.getShareUserId(),webUserDto.getUserId());
        return getSuccessResponseVO(null);
    }

    private SessionShareDto checkShare(HttpSession session,String shareId){
        SessionShareDto sessionShareFromSession = getSessionShareFromSession(session, shareId);
        if (sessionShareFromSession == null){
            throw new BusinessException(ResponseCodeEnum.CODE_903);
        }
        if (sessionShareFromSession.getExpireTime() != null && new Date().after(sessionShareFromSession.getExpireTime())){
            throw new BusinessException(ResponseCodeEnum.CODE_902);
        }
        return sessionShareFromSession;
    }

    private ShareInfoVO getShareInfoCommon(String shareId){
        FileShare share = fileShareService.getFileShareByShareId(shareId);
        if (share == null || (share.getExpireTime() != null && new Date().after(share.getExpireTime()))){
            throw new BusinessException(ResponseCodeEnum.CODE_902);
        }
        ShareInfoVO shareInfoVO = CopyTools.copy(share, ShareInfoVO.class);
        FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(share.getFileId(), share.getUserId());

        if (fileInfo == null || fileInfo.getDelFlag() != 2){
            throw new BusinessException(ResponseCodeEnum.CODE_902);
        }
        UserInfo userInfo = userInfoService.getUserInfoByUserId(fileInfo.getUserId());
        if (userInfo != null){
            shareInfoVO.setNickName(userInfo.getNickName());
        }
        shareInfoVO.setFileName(fileInfo.getFileName());
        shareInfoVO.setUserId(fileInfo.getUserId());
        return shareInfoVO;
    }
}
